package com.zjs.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Description Redis的字符串操作
 * @Author zhu_jinsheng[zhu_js@suixingpay.com]
 * @Date 2019/12/3 21:46
 * @Version 1.0
 */
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 字符串类型操作
     */
    public void stringTypeOperation() {
        //基础用法
        System.out.println("----------Redis字符串类型基础用法----------");
        //获取键值
        String value = redisTemplate.opsForValue().get("redis-testString");
        System.out.println("设置前:" + value);
        //设置键值
        redisTemplate.opsForValue().set("redis-testString", "testString");
        //设置过期时间2分钟
        redisTemplate.expire("redis-testString", 2, TimeUnit.MINUTES);
        //设置键值并设置过期时间
        //redisTemplate.opsForValue().set("redis-testString", "testString", 2, TimeUnit.MINUTES);
        value = redisTemplate.opsForValue().get("redis-testString");
        System.out.println("设置后:" + value);
        //更新缓存
        value = redisTemplate.opsForValue().getAndSet("redis-testString", "testStringNew");
        System.out.println("更新缓存并返回旧的键值:" + value);
        value = redisTemplate.opsForValue().get("redis-testString");
        System.out.println("更新后:" + value);
        redisTemplate.delete("redis-testString");
        value = redisTemplate.opsForValue().get("redis-testString");
        System.out.println("删除后:" + value);


        //设置键值自增自减操作
        System.out.println("----------Redis自增自减操作----------");
        //自增自减操作，若有这个键，则将键值加一或减一，没有则创建然后加一或减一，如果类型不是数字类型，则抛异常
        System.out.println("自增前:" + redisTemplate.opsForValue().get("redis-test-increment-number"));
        long number = redisTemplate.opsForValue().increment("redis-test-increment-number", 1);
        System.out.println("第1次自增：" + number);
        //设置过期时间
        redisTemplate.expire("redis-test-increment-number", 2, TimeUnit.MINUTES);
        number = redisTemplate.opsForValue().increment("redis-test-increment-number", 1);
        System.out.println("第2次自增：" + number);
        number = redisTemplate.opsForValue().increment("redis-test-increment-number", 1);
        System.out.println("第3次自增：" + number);
        number = redisTemplate.opsForValue().increment("redis-test-increment-number", -1);
        System.out.println("第1次自减：" + number);
        number = redisTemplate.opsForValue().increment("redis-test-increment-number", -1);
        System.out.println("第2次自减：" + number);

    }

    /**
     *
     */
    public void hashTypeOperation(){

    }
}
